//
//  MLXBaseCardScanViewController.m
//  Pods
//
//  Created by SY on 2019/1/28.
//

#import "MLXBaseCardScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "UIImage+Stream.h"
@interface MLXBaseCardScanViewController ()

// 是否打开手电筒
@property (nonatomic,assign,getter = isTorchOn) BOOL torchOn;
@property(nonatomic,strong) UIButton *torchBtn;
@end

@implementation MLXBaseCardScanViewController
#ifdef exbankcard
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addRightItem];
    [self addCloseButton];
    self.view.backgroundColor = [UIColor whiteColor];
}
#pragma mark - 添加关闭按钮
-(void)addCloseButton {
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    NSBundle *bundle = [NSBundle bundleForClass:self.class];
    NSString *img_path = [bundle pathForResource:@"idcard_back" ofType:@"png" inDirectory:@"MLXIdCardRecognition.bundle"];
    UIImage *image = [UIImage imageWithContentsOfFile:img_path];
    [closeBtn setImage:image forState:UIControlStateNormal];
    CGFloat closeBtnWidth = 40;
    CGFloat closeBtnHeight = closeBtnWidth;
    CGRect viewFrame = self.view.frame;
    closeBtn.frame = (CGRect){CGRectGetMaxX(viewFrame) - closeBtnWidth, CGRectGetMaxY(viewFrame) - closeBtnHeight, closeBtnWidth, closeBtnHeight};
    [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
}
-(void)addRightItem{
    NSBundle *bundle = [NSBundle bundleForClass:self.class];
    NSString *img_path = [bundle pathForResource:@"nav_torch_on" ofType:@"png" inDirectory:@"MLXIdCardRecognition.bundle"];
    UIImage *image = [UIImage imageWithContentsOfFile:img_path];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIButton *torchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [torchBtn addTarget:self action:@selector(turnOnOrOffTorch) forControlEvents:UIControlEventTouchUpInside];
    _torchBtn = torchBtn;
    [torchBtn setImage:image forState:UIControlStateNormal];
    [self.view addSubview:torchBtn];
    CGRect frame = [[UIApplication sharedApplication] statusBarFrame];
    torchBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 60, frame.size.height + 10, 40, 40);
    
}
#pragma mark 绑定“关闭按钮”的方法
-(void)close {
    UIViewController *vc = [self.navigationController popViewControllerAnimated:YES];
    if (vc == nil) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)turnOnOrOffTorch{
    self.torchOn = !self.isTorchOn;
    if (self.isTorchOn) {
        NSBundle *bundle = [NSBundle bundleForClass:self.class];
        NSString *img_path = [bundle pathForResource:@"nav_torch_off" ofType:@"png" inDirectory:@"MLXIdCardRecognition.bundle"];
        UIImage *image = [UIImage imageWithContentsOfFile:img_path];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.torchBtn setImage:image forState:UIControlStateNormal];
        [self.scanManager setFlashMode:AVCaptureTorchModeOn];
    }else{
        NSBundle *bundle = [NSBundle bundleForClass:self.class];
        NSString *img_path = [bundle pathForResource:@"nav_torch_on" ofType:@"png" inDirectory:@"MLXIdCardRecognition.bundle"];
        UIImage *image = [UIImage imageWithContentsOfFile:img_path];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.torchBtn setImage:image forState:UIControlStateNormal];
        [self.scanManager setFlashMode:AVCaptureTorchModeOff];
    }
}
-(MLXScanManager *)scanManager{
    if (!_scanManager) {
        _scanManager = [[MLXScanManager alloc]init];
    }
    return _scanManager;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self checkAuthorizationStatus];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.scanManager doSomethingWhenWillDisappear];
}
#pragma mark - 检测摄像头权限
-(void)checkAuthorizationStatus {
    AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (authorizationStatus) {
        case AVAuthorizationStatusNotDetermined:[self showAuthorizationNotDetermined]; break;// 用户尚未决定授权与否，那就请求授权
        case AVAuthorizationStatusAuthorized:[self showAuthorizationAuthorized]; break;// 用户已授权，那就立即使用
        case AVAuthorizationStatusDenied:[self showAuthorizationDenied]; break;// 用户明确地拒绝授权，那就展示提示
        case AVAuthorizationStatusRestricted:[self showAuthorizationRestricted]; break;// 无法访问相机设备，那就展示提示
    }
}
#pragma mark 用户还未决定是否授权使用相机
-(void)showAuthorizationNotDetermined {
    __weak __typeof__(self) weakSelf = self;
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        granted? [weakSelf showAuthorizationAuthorized]: [weakSelf showAuthorizationDenied];
    }];
}
#pragma mark 被授权使用相机
-(void)showAuthorizationAuthorized {
    [self.scanManager doSomethingWhenWillAppear];
}
#pragma mark 未被授权使用相机
-(void)showAuthorizationDenied {
    
    NSString *title = @"相机未授权";
    NSString *message = @"请到系统的“设置-隐私-相机”中授权此应用使用您的相机";
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 跳转到该应用的隐私设授权置界面
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertC addAction:cancelAction];
    [alertC addAction:okAction];
    [self presentViewController:alertC animated:true completion:nil];
}
#pragma mark 使用相机设备受限
-(void)showAuthorizationRestricted {
    NSString *title = @"相机设备受限";
    NSString *message = @"请检查您的手机硬件或设置";
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertC addAction:okAction];
    [self presentViewController:alertC animated:true completion:nil];
}
#endif
@end
